#include "PageBuilder.h"

PageBuilder::PageBuilder()
{
    this->pageCount_ = 0;
}

PageBuilder::~PageBuilder()
{
    this->close();
}

void PageBuilder::open(const char* path)
{
    this->close();
    this->input_.open(path);
}

void PageBuilder::close()
{
    if (this->input_.is_open())
        this->input_.close();
}

Page PageBuilder::nextPage()
{
    std::string text;
    if (this->input_.is_open())
    {
        while (this->hasNext())
        {
            std::string line;
            getline(this->input_, line);
            if ( ! isEndOfPage(line))
            {
                text.append(line);
                if (!this->input_.eof())
                    text.append("\n");
            }
            else
            {
                break;
            }
        }
    }
    else
    {
        throw InputException();
    }
    
    return Page(++(this->pageCount_), text);
}

bool PageBuilder::isEndOfPage(std::string& line)
{
    return line == "<<#>>";
}

bool PageBuilder::hasNext()
{
    return this->input_.peek() != std::char_traits<wchar_t>::eof();
}

std::ostream& operator<< (std::ostream& out, const Page& page)
{
    const int previewSize = 20;
    out << "Page[" << page.number_ << ": \"" << page.text_.substr(0, previewSize);
    if (page.text_.size() > previewSize)
        out << "...";
    out << "\"" << std::endl;
    return out;
}